// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// m [author] rhyme_lph
// I [email]  rhymelph@gmail.com
// d [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/my_invitations_entity.dart';
import 'package:finance_app/src/http_service/http_invitation_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/page/login/pending_invitation_page.dart';

class PendingInvitationProvider extends BaseProvider {
  @override
  Future get dataFuture => null;

  bool isSelect = false;

  List<MyInvitationsEntity> selectList = [];

  @override
  void initState() {
    super.initState();
    selectList.addAll(List.from(Config.myInvitations));
  }

  void onChangeSelect(MyInvitationsEntity e) {
    if (selectList.contains(e)) {
      selectList.remove(e);
    } else {
      selectList.add(e);
    }
    update();
  }

  void onNext() async {
    List<String> selectId =
        selectList.map((e) => e.companyId.toString()).toList();
    List<String> unselectId = Config.myInvitations
        .where((element) => !selectList.contains(element))
        .map((e) => e.companyId.toString())
        .toList();
    bool isSuccess = false;
    await post(HttpInvitationService.acceptInvited(selectId, unselectId),
        loadingTip: S.current.loading,
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      isSuccess = true;
    });
    if (isSuccess) {
      //判断有无公司
      if (Config.userProfile.defaultCompanyId == null && selectId.length > 0) {
        //无公司
        Config.userProfile.defaultCompanyId = selectId.first;
        await RProvider.myProvider.updateGlobalMap();
      }
      if (Config.userProfile.name == null) {
        Routes.navigateTo(RouterGenProviders.createAccountPage,
            clearStack: true);
      } else {
        Routes.navigateTo(RouterGenProviders.dashboardPage, clearStack: true);
      }
    }
  }
}
